//
//  AppDelegate.swift
//  HealthMonitoring
//
//  Created by YTYanK on 2018/3/22.
//  Copyright © 2018年 YTYanK. All rights reserved.
//

import UIKit
import CoreData
import IQKeyboardManagerSwift



@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var isUse: Bool =  UserDefaults.standard.bool(forKey: "isUse") //记录是否第一次使用， 默认false,
    
//    var isLogin: Bool =  NetRequestTool.shareInstance.token.count > 0 ? true : false  //UserDefaults.standard.set(str, forKey: "TOKEN")   //UserDefaults.standard.bool(forKey: "isLogin") //记录是否首页界面状态，默认 Login - false，首页- true
   
    var isLogin: Bool = UserDefaults.standard.bool(forKey: "hm_isLogin")
    var window: UIWindow?
    
    var manager : TIMManager = TIMManager.sharedInstance()

    //MARK: - AppDelegate 实例
    static let shared = UIApplication.shared.delegate as! AppDelegate
    
    private override init() {}
    
    // MARK: - 配置
    func configAppearance() {
       // 状态栏
       UIApplication.shared.statusBarStyle = UIStatusBarStyle.lightContent // 白色
       let statusBarView = UIApplication.shared.value(forKey: "statusBarWindow") as! UIView
       let statusBar = statusBarView.value(forKey: "statusBar") as! UIView
       
       if statusBar.responds(to: #selector(setter: UIView.backgroundColor)){
            statusBar.backgroundColor = UIColor.black
       }
        
        // 导航条
        let shadow = NSShadow()
        shadow.shadowColor = UIColor.white
        shadow.shadowOffset = CGSize.zero
        
        UINavigationBar.appearance().tintColor =  configure.shareConfigure.HMColor1//UIColor.red  // nva 返回的字体颜色
      //  UINavigationBar.appearance().backgroundColor = UIColor.blue
        UINavigationBar().titleTextAttributes =  [
            NSAttributedStringKey.foregroundColor:UIColor.orange,
            NSAttributedStringKey.font : UIFont.systemFont(ofSize: 25),
            NSAttributedStringKey.shadow : shadow
        ]
        
        UILabel.appearance().backgroundColor  = UIColor.clear // 背景颜色
        UILabel.appearance().tintColor = UIColor.black   // 默字体颜色
        UIButton().setTitleColor(UIColor.red, for: UIControlState.normal)
       
    }
    
    
    func switchMain(showMain: AnyObject?) {
        UserDefaults.standard.set(true, forKey: "hm_isLogin") // 记录登陆状态
        
        let storyBoard = UIStoryboard.init(name: "Main", bundle: nil)
        let viewController = storyBoard.instantiateInitialViewController() as! UITabBarController
        let window  =  self.window
        UIView.transition(with: window!, duration: 0.6, options: UIViewAnimationOptions.transitionFlipFromRight, animations: {
            let oldState = UIView.areAnimationsEnabled
            UIView.setAnimationsEnabled(false)
            window?.rootViewController  = viewController
            window?.makeKeyAndVisible()
            UIView.setAnimationsEnabled(oldState)
            
        }, completion: nil)
    }
   
    
    public func switchLogin(showLogin: AnyObject?) {
//        UserDefaults.standard.removeObject(forKey: "hm_user")  //清空 users 信息
//        UserDefaults.standard.removeObject(forKey: "hm_info")
////        UserDefaults.standard.removeObject(forKey: "TOKEN")
//        NetRequestTool.shareInstance.token = ""  //清空 token
    
//        HMLoginParam.wipeData()
//        let storyBoard = UIStoryboard.init(name: "Login", bundle: nil)
//        let viewController = storyBoard.instantiateInitialViewController() as! UINavigationController
//        let window = self.window
//        window?.rootViewController = viewController
//        window?.makeKeyAndVisible()
    
    
    
        HMLoginParam.wipeData()
        let loginVc =  Login()
        let navC = UINavigationController.init(rootViewController: loginVc)

        self.window?.rootViewController = navC
        self.window?.makeKeyAndVisible()
    }
    /// 设置导航栏透明
//    open func setNavigationBarTranslucent() {
//
//    }
    
    

     // MARK: - 周期
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        configAppearance()
        configImSDK()
        configWxSDK()
        // 键盘
        IQKeyboardManager.shared.shouldResignOnTouchOutside = true
        IQKeyboardManager.shared.enable = true
        
        if isLogin { // true
             switchMain(showMain: nil)
        }else { //false
             switchLogin(showLogin: nil)
        }
//        // 登陆IM
        if UserDefaults.standard.string(forKey: "hm_sig") != nil {
            HMPlatform.getLoginSig()
        }
        return true
    }
    //讲离开
    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }
   //
    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }
    // 应用程序将进入前台
    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
       // UserDefaults.standard.set(self.orderId, forKey: "WXOrderId")
        if (UserDefaults.standard.string(forKey: "WXOrderId") != nil) {
            let orderId = UserDefaults.standard.string(forKey: "WXOrderId") //订单id 记得清空
            // 咨询id
            let consultId = UserDefaults.standard.string(forKey: "WXConsultId")
            // 医生id
            let doctorId = UserDefaults.standard.string(forKey: "WXDoctorId")
            
            //获取支付结果
            NetRequestTool.shareInstance.met = .get
            NetRequestTool.request(url: "user/order/check", parameters: ["orderId": orderId as Any], success: { (json) in
                print("======>>", json)
                if json["code"].intValue == 0 {

                    let currentUserId =  HMPlatform.getCurrentUserId()
                    // 会话ID（通过后台的规则） 对方id +  自己id
                    let conversationId = doctorId! + currentUserId
                    self.bindingConversation(consultId!, conversationId, doctorId: orderId!)

                    
                    // 进入聊天
                    let storyBoard = UIStoryboard(name: "Main", bundle: nil)
                    let _im : InstantMessaging = storyBoard.instantiateViewController(withIdentifier: "IM") as! InstantMessaging
                    self.window?.rootViewController?.pushViewController(_im)
                }else {

                }
                // 发一条信息
            }, fail: { (code, err) in
                print("======>>",code, err)
                 UserDefaults.standard.removeObject(forKey: "WXOrderId")
                 RKDropdownAlert.title("温馨提醒!", message: "支付失败！")
            }) {
            
            
            }
        }
        
        
        
    }
    // 激活
    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
        
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        // Saves changes in the application's managed object context before the application terminates.
        self.saveContext()
    }

    // MARK: - Core Data stack

    lazy var persistentContainer: NSPersistentContainer = {
        /*
         The persistent container for the application. This implementation
         creates and returns a container, having loaded the store for the
         application to it. This property is optional since there are legitimate
         error conditions that could cause the creation of the store to fail.
        */
        let container = NSPersistentContainer(name: "HealthMonitoring")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                 
                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()

    // MARK: - Core Data Saving support
    func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }

}

extension AppDelegate {
    /*
     初始化，配置IMSDK
     */
    func configImSDK() {
        let platform =  HMPlatform.sharePlatform
        platform.config(cfg: "1")
    }
    
    /*
     初始化 微信支付
     */
    
    func configWxSDK() {
        WXApi.registerApp(configure.shareConfigure.wxAppID)
    }
    
    /*
     绑定
     */
    func bindingConversation(_ consultId: String, _ conversationId: String, doctorId: String) {
        NetRequestTool.shareInstance.met = .post
        NetRequestTool.request(url: "doctor/consult/conversation", parameters: ["consultId": consultId, "conversationId": conversationId], success: { (doJson) in
            
            let con :TIMConversation = HMPlatform.getSomeoneConversation(doctorId)
            HMElem.foundConversation(con)
            
//            self.addFriend(id: doctorId) //加医生为好友
        }, fail: { (doCode, doErr) in
            print("doctor/consult/conversation ==========>",doCode)
        }) {
        
        }
    }
    
    // 请求添加好友
    func addFriend (id: String) {
        var users = Array<Any>()
        let reg:TIMAddFriendRequest = TIMAddFriendRequest()
        //添加好友
        reg.identifier = String.init(cString: id, encoding: String.Encoding.utf8)
        reg.remark = String.init(cString: "添加备注", encoding: String.Encoding.utf8)
        reg.addWording = String.init(cString: "添加理由", encoding: String.Encoding.utf8)
        //        reg.friendGroup = String.init(cString: "医生", encoding: String.Encoding.utf8)
        users.append(reg)
        
        
        TIMFriendshipManager.sharedInstance()?.addFriend(users, succ: { (ary) in
            for  res  in ary! {
                let fri :TIMFriendResult = res as! TIMFriendResult
                if  fri.status != .FRIEND_STATUS_SUCC  {
                    // 发一条消息
                    let con :TIMConversation = HMPlatform.getSomeoneConversation(id)
                    HMElem.foundConversation(con)
                    
                }else if fri.status == .ADD_FRIEND_STATUS_ALREADY_FRIEND  { // 已经是好友
                    let con :TIMConversation = HMPlatform.getSomeoneConversation(id)
                    HMElem.foundConversation(con)
                }else {
                    print("err =====>>>\(fri.identifier, fri.status)")
                }
                
            }
            
            
        }, fail: { (code, err) in
            print("add friend fail: \(code) ===> \(err)")
        })
    }
    
}
